﻿using Microsoft.AspNetCore.Http;
using System;

namespace ZhongKeSite.Common.Helper
{
    public static class CookieHelper
    {
        #region Cookie操作
        /// <summary>
        /// 添加cookie缓存不设置过期时间
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>

        public static void AddCookie(this HttpContext httpContext, string key, string value)
        {
            try
            {
                httpContext.Response.Cookies.Append(key, value);
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
            }
        }
        /// <summary>
        /// 添加cookie缓存设置过期时间
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="time">秒</param>
        public static void AddCookie(this HttpContext httpContext, string key, string value, int time)
        {
            httpContext.Response.Cookies.Delete(AppSettings.LoginVerifyCookieName);

            httpContext.Response.Cookies.Append(AppSettings.LoginVerifyCookieName, value, new CookieOptions
            {
                Expires = DateTime.Now.AddSeconds(AppSettings.CookieExpire)
            });
        }
        /// <summary>
        /// 删除cookie缓存
        /// </summary>
        /// <param name="key"></param>
        public static void DeleteCookie(this HttpContext httpContext, string key)
        {
            httpContext.Response.Cookies.Delete(key);
        }
        /// <summary>
        /// 根据键获取对应的cookie
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetCookieValue(this HttpContext httpContext, string key)
        {
            var value = string.Empty;
            httpContext.Request.Cookies.TryGetValue(key, out value);
            return value;
        }
        #endregion
    }
}
